package com.heima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.domain.vos.ApUserVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //从数据库核对前端传过来的账号，并返回该用户
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        //如果从数据库查询为空，则直接return
        if (ObjectUtil.isEmpty(apUser)||ObjectUtil.isNull(apUser)){
            log.error("[用户查询]错误");
            return ResponseResult.errorResult(2,"账号不存在");
        }
        //验证用户的密码
        String password = dto.getPassword();
        boolean checkpw = BCrypt.checkpw(password, apUser.getPassword());
        if (checkpw){
            //用户验证成功
            //生成jwt令牌返回给前端
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            log.info("[jwt令牌]：{}",token);
            //将用户apuser 和 token 令牌赋给apuservo
            ApUserVo apUserVo = ApUserVo.builder()
                    .apUser(apUser)
                    .token(token)
                    .build();
            return ResponseResult.okResult(apUserVo);
        }else {
            //用户验证失败
            log.error("[密码错误]");
            return ResponseResult.errorResult(2,"密码错误");
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
